package rpc.client.main;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.ipc.RPC;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rpc.server.MyInterface;

import java.io.*;
import java.net.InetSocketAddress;

/**
 * ClientMain
 *
 * @author zhangyimin
 * @version 1.0
 * @date 2018-07-27 下午3:27
 */
public class ClientMain {


    public static Configuration configuration;
    public final  static  String hostName="zymMBP";
    public final  static  int port=7788;
    public static FileSystem fs;

    /**
     * 测试RPC协议
     * @throws IOException
     */
    @Test
    public void testClient() throws Exception {
        MyInterface proxy= RPC.getProxy(MyInterface.class,
                MyInterface.versionID,
                new InetSocketAddress(hostName,port),
                configuration);
        String result=proxy.sayHello("zhangyimin");

        System.out.println(result);

    }

    @Before
    public void setConfig() throws IOException {
        configuration = new Configuration();
        configuration.set("fs.defaultFS", "hdfs://10.16.7.37:9000");
        fs=FileSystem.get(configuration);
    }



    //赋权方式1
//        System.setProperty("HADOOP_USER_NAME","macbookpro");
    //赋权方式2
//        在junit中设置-D的参数  -ea -DHADOOP_USER_NAME=macbookpro
//        创建文件夹
    @Test
    public void testMkDir() throws IOException {
        boolean isSuccess = fs.mkdirs(new Path("/data/test07253"));
        if (isSuccess) {
            fs.close();
            System.out.print("操作成功!");
        }

    }


    /**
     * hadoop实现上传和下载
     *
     * @throws IOException
     */
    @Test
    public void testUpload1() throws IOException {
        InputStream inputStream = new FileInputStream("/Users/zhangyimin/Downloads/log.xml");
        OutputStream outputStream = fs.create(new Path("/tools/log123.xml"));
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    @Test
    public void testUpload2() throws IOException {
        InputStream inputStream = new FileInputStream("/Users/zhangyimin/Downloads/log.xml");
        OutputStream outputStream = fs.create(new Path("/tools/log124.xml"));
        IOUtils.copyBytes(inputStream, outputStream, 1024);
    }


    @Test
    public void testDownload() throws IOException {
        InputStream inputStream = fs.open(new Path("/tools/log124.xml"));
        OutputStream outputStream = new FileOutputStream("/Users/zhangyimin/Downloads/log125.xml");
        IOUtils.copyBytes(inputStream, outputStream, 1024);
    }


    @After
    public void closeFS() throws IOException {
        fs.close();
    }


}
